package com.huichenghe.xinlvsh01.slide;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.usage.UsageEvents;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.app.LoaderManager.LoaderCallbacks;

import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;

import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import com.huichenghe.xinlvsh01.MainActivity;
import com.huichenghe.xinlvsh01.R;
import com.huichenghe.xinlvsh01.Utils.LocalDataSaveTool;
import com.huichenghe.xinlvsh01.Utils.MyConfingInfo;
import com.huichenghe.xinlvsh01.Utils.MyToastUitls;
import com.huichenghe.xinlvsh01.Utils.SaveImageUtil;
import com.huichenghe.xinlvsh01.Utils.WebGlobalConfig;

import org.w3c.dom.Text;


/**
 * 实现LoaderCallbacks 是为了异步查询联系人数据库，做自动补全操作
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor>
{
    public static final String TAG = LoginActivity.class.getSimpleName();

    /**
     * A dummy authentication store containing known user names and passwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[]{
            "foo@example.com:hello", "bar@example.com:world"
    };
    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;
    private EditText mPasswordView;
    private View mProgressView;
    private View mLoginFormView;
    private TextView forget_pwd;
    private LinearLayout mLinearLayout;
    private ImageButton back;
    private boolean isFirstLayout = true;
    private int whereAreYouFrom;

    // 缓存中的个人信息包括账号密码
    private String info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
    }

    @Override
    protected void onResume()
    {
        super.onResume();

    }

    // 初始化，拿到控件对象
    private void init() {
        back = (ImageButton)findViewById(R.id.back_to_login);
        back.setOnClickListener(listenerForClick);

        mLinearLayout = (LinearLayout)findViewById(R.id.get_password_layout);

        forget_pwd = (TextView)findViewById(R.id.forget_the_pwd);
        forget_pwd.setOnClickListener(listenerForClick);


        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        populateAutoComplete();

        mPasswordView = (EditText) findViewById(R.id.password);
        // 设置有编辑动作时监听
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(listenerForClick);

        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }

    private void populateAutoComplete() {
        getLoaderManager().initLoader(0, null, this);
    }


    View.OnClickListener listenerForClick = new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            switch (v.getId())
            {
                case R.id.email_sign_in_button:
                    // 检查输入格式并登陆
                    attemptLogin();
                    break;

                case R.id.forget_the_pwd:
                    // 点击 ？号， 显示找回密码布局
                    showTheGetPwdLayoutWithAnim(forget_pwd, mLinearLayout);
                    isFirstLayout = false;

//                    mLinearLayout.setVisibility(View.VISIBLE);
                    break;
                case R.id.back_to_login:    // 返回按钮
//                    mLinearLayout.setVisibility(View.GONE);
                    hideTheGetPwdLayoutWithAnim(forget_pwd, mLinearLayout);
                    isFirstLayout = true;
                    break;
            }

        }
    };


    /**
     * 判断此页面是由哪里启动的并做出相应操作，最终进入MainActivity
     */
    private void judgeAndEnterMainAcitivity()
    {
        int from = getIntent().getIntExtra(MyConfingInfo.WHERE_ARE_YOU_FROM, -1);

        if(from == MyConfingInfo.FROM_THE_MAINACTIVITY)
        {
            LoginActivity.this.onBackPressed();
        }else
        {
            Intent mIntent = new Intent(LoginActivity.this, MainActivity.class);
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(mIntent);
            LoginActivity.this.finish();
        }

    }


    /**
     * 显示动画
     * @param tv
     * @param ml
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void showTheGetPwdLayoutWithAnim(TextView tv, LinearLayout ml)
    {
        // 执行圆形动画
        int[] location = new int[2];            // 两个元素的数组
        tv.getLocationOnScreen(location);
        int x = location[0] + (tv.getWidth()/2);                    // 圆心x轴
        int y = location[1];                    // 圆心y轴

        // get the final radius for the clipping circle
        int finalRadius = Math.max(ml.getWidth(), ml.getHeight());  // 最大半径
        int minRadius = tv.getWidth()/2;        // 最小半径

        // create the animator for this view (the start radius is zero)
        Animator anim =
                ViewAnimationUtils.createCircularReveal(ml, x, y, minRadius, finalRadius);

        // make the view visible and start the animation
        ml.setVisibility(View.VISIBLE);
        anim.start();



    }


    /**
     * 隐藏动画
     * @param vg
     * @param layout
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void hideTheGetPwdLayoutWithAnim(TextView vg, final LinearLayout layout)
    {
        int[] location = new int[2];
        vg.getLocationOnScreen(location);
        int cxx = location[0] + (vg.getWidth()/2);
        int cyy = location[1]* 7;
//        int cyy = vg.getMeasuredHeightAndState();

//        int cxx = (int)vg.getX();
//        int cyy = (int)vg.getY();

        // get the initial radius for the clipping circle
        // 获取园的半径
        int initialRadiuss = layout.getHeight();    // 最大半径
        int minRadiuss = vg.getWidth()/2;             // 最小半径

        // create the animation (the final radius is zero)
        Animator anims =
                ViewAnimationUtils.createCircularReveal(layout, cxx, cyy, initialRadiuss, minRadiuss);

        // make the view invisible when the animation is done
        anims.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                   layout.setVisibility(View.GONE);
            }
        });

        // start the animation
        anims.start();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK)
        {
            if(!isFirstLayout)
            {
                hideTheGetPwdLayoutWithAnim(forget_pwd, mLinearLayout);
                isFirstLayout = true;
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin()
    {
        if (mAuthTask != null) {        // 判断异步任务对象
            return;
        }

        // Reset errors.
        mEmailView.setError(null);      // 复位错误提示
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        // 获取用户输入内容
        String account = mEmailView.getText().toString();
        String password = mPasswordView.getText().toString();

        Log.i(TAG, "账号：" + account + "密码：" + password);

        boolean cancel = false; // 代表没有通过验证
        View focusView = null;  // 没通过验证的view

        // Check for a valid password, if the user entered one.
        // 检查密码是否可用，
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // 检查账号是否可用
        if (TextUtils.isEmpty(account)) {   // 非空验证
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        }  else if (!isEmailValid(account)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();   // 没通过验证的获取焦点
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(account, password);
            mAuthTask.execute((Void) null);
        }
    }

    private boolean isEmailValid(String email) {
        //TODO: Replace this with your own logic
        return email.length() >= 4;
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() >= 6;
    }

    /**
     * 显示进度条，并隐藏login布局
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView
                    .animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 0 : 1)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                        }
                    });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView
                    .animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 1 : 0)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                        }
                    });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this,
                // Retrieve data rows for the device user's 'profile' contact.
                Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                                     ContactsContract.Contacts.Data.CONTENT_DIRECTORY),
                                     ProfileQuery.PROJECTION,

                // Select only email addresses.
                ContactsContract
                        .Contacts
                        .Data
                        .MIMETYPE +
                        " = ?",
                new String[]{
                         ContactsContract
                        .CommonDataKinds
                        .Email
                        .CONTENT_ITEM_TYPE},

                // Show primary email addresses first. Note that there won't be
                // a primary email address if the user hasn't specified one.
                ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(
            Loader<Cursor> cursorLoader,
            Cursor cursor)
    {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast())
        {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }
        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {

    }

    private interface ProfileQuery
    {
        String[] PROJECTION = {
                ContactsContract.CommonDataKinds.Email.ADDRESS,
                ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
        };

        int ADDRESS = 0;
        int IS_PRIMARY = 1;
    }


    private void addEmailsToAutoComplete(List<String> emailAddressCollection)
    {
        //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter =
                new ArrayAdapter<>(LoginActivity.this,
                        android.R.layout.simple_dropdown_item_1line, emailAddressCollection);

        mEmailView.setAdapter(adapter);
    }


    /**
     * 异步登录/注册
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private String mAccount;    // 账号
        private String mPassword;   // 密码

        UserLoginTask(String account, String password) {
            mAccount = account;
            mPassword = password;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            boolean isSuccess = false;
            Sub_login login = null;

            try {

                login = new Sub_login(LoginActivity.this);// 登陆帮助类

                isSuccess = login.requestLogin(mAccount, mPassword);    // 发送账号密码
                Log.i("", "登陆返回结果：-----" + isSuccess);

            } catch (IOException e) {
                e.printStackTrace();
            }

            if(isSuccess)       // 登陆成功
            {
                if(login != null)   // 对象不为空
                {
                    Bitmap mB = login.getImageIcon();
                    if(mB != null)
                    {
                        // 将Bitmap存入缓存
                        SaveImageUtil.saveImageToSD(mB, MyConfingInfo.IMAGEVIEW_SAVE_PATH, File.separator + "tmp.jpeg");

                                // 获取图片成功，将图片转为byte数组
//                        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
//                        boolean isOK = mB.compress(Bitmap.CompressFormat.JPEG, 100, byteOut);

//                            bytesImage = byteOut.toByteArray();
                                LocalDataSaveTool.getInstance(LoginActivity.this).writeSp(MyConfingInfo.USER_ACCOUNT, mAccount);
                            LocalDataSaveTool.getInstance(LoginActivity.this).writeSp(MyConfingInfo.USER_PASSWORD, mPassword);
                            return true;
                    }
                }
            }


//            for (String credential : DUMMY_CREDENTIALS) {
//                String[] pieces = credential.split(":");
//                if (pieces[0].equals(mEmail)) {
//                    // Account exists, return true if the password matches.
//                    return pieces[1].equals(mPassword);
//                }
//            }

            // TODO: register the new account here.
            return false;
        }




        @Override
        protected void onPostExecute(final Boolean success)
        {
            mAuthTask = null;
            showProgress(false);

            if (success) {
                Toast.makeText(LoginActivity.this, getString(R.string.login_success), Toast.LENGTH_SHORT).show();
                Intent mIntent = new Intent();
                mIntent.setClass(LoginActivity.this, MainActivity.class);
                mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(mIntent);
                finish();
            } else {
                MyToastUitls.showToast(LoginActivity.this, R.string.login_wrong, 1);
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

